import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:dio/native_imp.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:nft_shop/login/controller/user_controller.dart';
import 'package:nft_shop/login/page/login_page.dart';

export 'package:dio/dio.dart';

// 必须是顶层函数
_parseAndDecode(String response) {
  return jsonDecode(response);
}

parseJson(String text) {
  return compute(_parseAndDecode, text);
}

abstract class BaseHttp extends DioForNative {
  BaseHttp() {
    /// 初始化 加入app通用处理
    (transformer as DefaultTransformer).jsonDecodeCallback = parseJson;
    init();
  }

  void init();
}

/// 子类需要重写
abstract class BaseResponseData {
  int? code = 0;
  String? msg;
  dynamic? data;

  bool get success;

  BaseResponseData({this.code, this.msg, this.data});

  @override
  String toString() {
    return 'BaseRespData{code: $code, message: $msg, data: $data}';
  }
}


/// 接口的code没有返回为true的异常
class NotSuccessException implements Exception {
  String? msg;

  NotSuccessException.fromRespData(BaseResponseData respData) {
    msg = respData.msg;
  }

  @override
  String toString() {
    return 'NotExpectedException{respData: $msg}';
  }
}

/// 用于未登录跳登陆界面
class UnAuthorizedException implements Exception {
  UnAuthorizedException(){
    Future.delayed(Duration(seconds: 0)).then((onValue) {
      if(UserController.to.isLogin){
        UserController.to.clearUser();
        EasyLoading.showToast(this.toString());
        Get.to(LoginPage());
      }
    });
  }

  @override
  String toString() => '登录过期请重新登录';
}

